<template>
  <div class="wrapper">
    <div class="title">
      <el-icon><ShoppingCart/></el-icon>
      我的购物车

    </div>

    <el-table
        :data="tableData.carts"
        :header-cell-style="{background:'#fff5e9',color:'#9d6520',}"
        @selection-change="handleSelectionChange">
      <!-- 选择框 -->
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope" >
          <div @click="goGoodsInfo(scope.row)">
            <img :src="getPath(scope.row.goods.imagePathList[0])" style="width: 100%;height: 100px;width: 100px;" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品" width="400px">
        <template #default="scope">
          <span >{{scope.row.goods.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价（元)" >
        <template #default="scope">
          <span class="price-icon">￥</span>
          <span class="price">{{scope.row.goods.price}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="180px">
        <template #default="scope">
          <div class="num-container">
            <el-button :icon="Minus" @click="minus(scope.row)" :disabled="scope.row.cart.count === 1"/>
            <!-- 在写input-style时，要注意使用JavaScript语法来返回对象 用 -->
            <el-input v-model="scope.row.cart.count" :input-style="{'text-align': 'center',}" disabled></el-input>
            <el-button :icon="Plus" @click="plus(scope.row)" :disabled="scope.row.cart.count === scope.row.goods.store"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="小计" width="100px">
        <template #default="scope">
          <span class="price-icon">￥</span>
          <span class="price">{{calculateSum(scope.row)}}</span>

        </template>
      </el-table-column>
      <el-table-column label="操作" width="80px">
        <template #default="scope">
          <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
        </template>

      </el-table-column>

    </el-table>

    <div style="padding-top: 20px;">
      <el-button type="danger" size="default" @click="order()" style="margin-right: 100px;">下单已选商品</el-button>
      <el-button type="info" size="default" @click="delSelect()">删除已选商品</el-button>
    </div>

  </div>
</template>

<script setup>
import { getCookieForObject,setCookiesFromObject} from '@/util';
import { getPath } from '@/util';
import { ElMessage,ElMessageBox } from 'element-plus';
import router from '@/router';
import { Plus, Minus } from '@element-plus/icons-vue'
import { ShoppingCart } from '@element-plus/icons-vue'
import { reactive,ref } from 'vue'
import { get,post } from '@/plugins/axios'
const multipleSelection=ref([])
const radio1 = ref(2)
const data = reactive([
  {
    imgs: '',
    name:'',
    price: 19.90,
    num: 4,
    sum: 59.7,
    store: 10
  }
])
const tableData = reactive({
  carts:[],
  pages: 0,
  total: 0
})
const account=ref()
const params = reactive({
  userId:0,
  pageNo: 1,
  pageSize: 10
})
list()
function init(){
  const userinfo= getCookieForObject('user')
  if (userinfo) {
    params.userId=userinfo.id
    account.value=userinfo.account
  }
  console.dir(params.userId)
}
function minus(row) {
  if (row.cart.count > 1) {
    row.cart.count--
    calculateSum(row)
  } else{

  }
  post("/cart/update",{id:row.cart.id,count:row.cart.count},content=>{
  })
}
function calculateSum(row) {
  return parseFloat(row.cart.count * row.goods.price).toFixed(2)
}
function plus(row) {
  // 条件为小于库存
  if(row.cart.count < row.goods.store) {
    row.cart.count++
    calculateSum(row)
  } else{
    console.dir('不够了')
  }
  post("/cart/update",{id:row.cart.id,count:row.cart.count},content=>{
  })
}
function del(row) {
  console.dir(row.cart.id)
  post("/cart/del",{id:row.cart.id},content=>{
    ElMessageBox.confirm(
        '是将该商品移出购物车？',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    )
        .then(() => {

          ElMessage({
            type: 'success',
            message: '已从购物车中移除该商品',
          })


        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消移除',
          })
        })
        .finally(()=>{
          window.location.reload()
        })
  })

}

function list(){
  init()
  console.dir(params)
  get("/cart/list",{userId:params.userId,pageNo:params.pageNo,pageSize:params.pageSize},content=>{
    console.dir(content)

    for(const index in content.records){
      tableData.carts.push({"cart":content.records[index],"goods":getgoods(content.records[index].goodsId)})
    }
    console.dir(tableData.carts)
  })
}

function getgoods(goodsid){
  const goods=ref()
  console.dir(goodsid)
  get('/goods/getById',{'id':goodsid},content=>{
    console.dir(content)
    goods.value=content
  })
  console.dir(goods)
  return goods
}

const goGoodsInfo= (row)=>{
  router.push({
    path:'/goodsInfo',
    query:{goodsId:row.goods.id}
  })
}

function handleSelectionChange(val) {
  // val 是选中行的数据数组
  multipleSelection.value = val;
  console.log('选中行的数据：', val);
  console.dir(multipleSelection.value)
}

function order(){
  if(multipleSelection.value.length>0){
    ElMessageBox.confirm(
        '是否将选定商品创建一个订单？',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    )
        .then(() => {
          const userId=ref()
          userId.value= params.userId
          const totalAmount=ref(0)
          const goodsIds=ref([])
          const counts=ref([])
          const storeId=ref()
          storeId.value=radio1.value
          for(const key in multipleSelection.value){
            goodsIds.value.push(multipleSelection.value[key].cart.goodsId)
            counts.value.push(multipleSelection.value[key].cart.count)
            totalAmount.value+=parseFloat(multipleSelection.value[key].cart.count * multipleSelection.value[key].goods.price)
          }
          console.dir(goodsIds.value)
          console.dir(counts.value)
          console.dir(totalAmount.value)
          if (account.value >= totalAmount.value) {
            console.dir(111111111)
            post("/orders/createOrder",
                {userId:userId.value,totalAmount:totalAmount.value,goodsIds:goodsIds.value,counts:counts.value,storeId:storeId.value},
                content => {
                  for(const key in multipleSelection.value){
                    post("/cart/del",{id:multipleSelection.value[key].cart.id},content=>{})
                  }
                  router.push({
                    path: '/create-orders',
                    query: { id: content }
                  })
                })
          }
          else {
            ElMessageBox.confirm( '您的余额不足，是否充值？', '警告', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning'
            })
                .then(() => {
                  router.push('/recharge')
                })
          }


        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消下单',
          })
        })
        .finally(()=>{
          //window.location.reload()
        })
  }
  else{
    ElMessage({
      type: 'warning',
      message: '请勾选要下单的商品',
    })
  }

}

function delSelect(){
  if(multipleSelection.value.length>0){
    console.dir(multipleSelection.value)
    ElMessageBox.confirm(
        '是否将选中商品移出购物车？',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    )
        .then(() => {
          for(const key in multipleSelection.value){
            post("/cart/del",{id:multipleSelection.value[key].cart.id},content=>{})
          }

          ElMessage({
            type: 'success',
            message: '已从购物车中移除选中商品',
          })


        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消移除',
          })
        })
        .finally(()=>{

          window.location.reload()
        })
  }
  else{
    ElMessage({
      type: 'warning',
      message: '请勾选要删除的商品',
    })
  }


}
</script>

<style scoped lang="scss">
.wrapper{
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  padding-bottom: 60px;
  .title{
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    width: 1100px;
    height: 40px;
    font-size: 22px;
    font-weight: 600;
    margin-top: 30px;
    text-align: center;
    line-height: 40px;
    margin-right: auto;
    margin-left: auto;
    background-color: #ddeece;
    border-radius: 5px;
    .el-icon{
      margin-right: 8px;
    }
    }

  }
  .el-table{
    width: 1100px;
    margin-top: 26px;
    .num-container{
      display: flex;
      .el-input{
        margin-left: 5px;
        margin-right: 5px;
        width: 40px;
      }
      .el-button{
        width: 40px;
        height: 35px;
      }
    }
    .price-icon{
      color: #ff6200;
      font-size: 12px;
      font-weight: 700;
      line-height: 16px;
    }
    .price{
      color: #ff6200;
      font-size: 16px;
      font-weight: 700;
      line-height: 36px;
    }
  }

</style>